package com.hud.easynavi;


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.SparseArray;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;

import java.util.Timer;
import java.util.TimerTask;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;
import protocol.FcwLdwUpdateInfo;
import protocol.NaviUpdateInfo;
import protocol.ProtoMsg;

public class MainActivity extends Activity {
    final static  String TAG = "MainActivity";
    boolean isEmulated = false;// 模拟车速/电量/导航箭头
    Handler handler;
    TextView tv_car_speed;
    TextView tv_remain_distance;
    TextView tv_next_road_distance;
    TextView tv_gear_level;
    ImageView iv_gear_level;
    ImageView iv_left_lane;
    ImageView iv_right_lane;
    ImageView iv_next_turn_tip;

    ImageView iv_road_center;
    CanDataThread can0;
    CanDataThread can1;
    ArcProgressView battery_remain_power;
    GearLevel gearLevel;
    SerialPortReceiveThread serialPortReceiveThread;
    SparseArray<Integer> ldw_road_status = new SparseArray<Integer>();

    ImageView iv_turn_left;
    ImageView iv_turn_right;
    ImageView iv_tire_pressure;
    View ldw_area;
    View navi_info_panel;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
//        WindowManager.LayoutParams lp = getWindow().getAttributes();
//        lp.width =480;
//        lp.height= 120;
//        lp.gravity = Gravity.LEFT |Gravity.TOP;
//        lp.y = 120;
//        getWindow().setAttributes(lp);

        setContentView(R.layout.activity_ep21_simple_navi);

        gearLevel = new GearLevel();

        // 剩余电量
        battery_remain_power = (ArcProgressView)findViewById(R.id.oil_level_panel);
        battery_remain_power.setMaxProgress(102.3f);
        battery_remain_power.setMinProgress(0f);
        battery_remain_power.setProgressValue(0f);// 当前值 初始化
        battery_remain_power.setArc1_k(0.99f);
        battery_remain_power.setArc2_k(0.80f);
        battery_remain_power.setPanelBoxPaddingTop(10);
        battery_remain_power.showTextInfo(false); //
        // 当前车速
        tv_car_speed = (TextView)findViewById(R.id.car_speed);
        tv_car_speed.setText("0");
        tv_remain_distance = (TextView)findViewById(R.id.tv_mileage);
        tv_remain_distance.setText("0");
        tv_next_road_distance = (TextView)findViewById(R.id.tv_next_road_distance);
        tv_next_road_distance.setText("--");

        // ldw 数据
        iv_left_lane = (ImageView) findViewById(R.id.iv_ldw_leftLane);
        iv_right_lane = (ImageView)findViewById(R.id.iv_ldw_rightLane);
        iv_road_center = (ImageView)findViewById(R.id.iv_ldw_road_center);
        ldw_road_status.put(1,R.drawable.ldw_car);
        ldw_road_status.put(2,R.drawable.ldw_motorcycle);
        ldw_road_status.put(3,R.drawable.ldw_pedistrian);

        // 当前档位
        tv_gear_level = (TextView) findViewById(R.id.tv_gear_level);
        handler = new Handler();
        // 下一个路口转向提示
        iv_next_turn_tip = (ImageView)findViewById(R.id.iv_next_road_turn_tip);

        iv_turn_left = (ImageView)findViewById(R.id.iv_turn_left);
        iv_turn_right = (ImageView)findViewById(R.id.iv_turen_right);
        ldw_area = findViewById(R.id.ldw_area);
        iv_tire_pressure = (ImageView)findViewById(R.id.iv_tire_pressure);
        navi_info_panel = findViewById(R.id.navi_info_panel);

        if(isEmulated){
            Timer tm = new Timer();
            tm.scheduleAtFixedRate(new TimerTask() {
                int speed = 36;
                int mileage = 300;
                int next_road_dist = 100;
                int index = 0;
                float power_value = 0.0f;
                boolean on_off = true;

                @Override
                public void run() {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            if(speed > 300)
                                speed = 0;
                            speed ++;

                            if(mileage > 10000)
                                mileage = 300;
                            mileage ++;

                            if(next_road_dist > 10000)
                                next_road_dist = 10;
                            next_road_dist ++;

                            if(power_value > 102.3f){
                                power_value = 0;
                            }
                            power_value += 1.0f;

                            battery_remain_power.setProgressValue(power_value);

                            tv_car_speed.setText(Integer.toString(speed));
                            tv_remain_distance.setText(Integer.toString(mileage));
                            tv_next_road_distance.setText(Integer.toString(next_road_dist)+"m");

                            tv_gear_level.setText(gearLevel.getLevelById(index++ % 13));

                            iv_next_turn_tip.setBackgroundResource(
                                    ResourceUtil.getIcon(MainActivity.this,
                                            "icon_type_",Integer.toString(index++ % 25)));
                            iv_road_center.setBackgroundResource(
                                    on_off?R.drawable.ldw_motorcycle:R.drawable.ldw_pedistrian);

                            iv_left_lane.setBackgroundResource(
                                    on_off?R.drawable.ldw_left_lane_on:R.drawable.ldw_left_lane_off);

                            iv_right_lane.setBackgroundResource(
                                    on_off?R.drawable.ldw_right_lane_on:R.drawable.ldw_right_lane_off);

                            on_off = !on_off;
                        }
                    });
                }
            },1000,500);
        }

        // CAN 数据解析
        CanDataParser.getInstance().setListener(new CanDataParser.Listener() {
            @Override
            public void onCanMsgSignal(int can_id, boolean valid, String signal, final float value_f, final int value_i) {
                switch (can_id){
                    case CAN_ID.car_speed:// 更新车速
                        //if(valid)
                        {
                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    tv_car_speed.setText(Integer.toString((int)value_f));
                                }
                            });
                        }
                        break;
                    case CAN_ID.gear_level://更新档位
                        //if(valid)
                        {
                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    tv_gear_level.setText(gearLevel.getLevelById(value_i));
                                }
                            });
                        }
                        break;
                    case CAN_ID.remain_battery_power:// 更新剩余电量
                        //if(valid)
                        {
                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    battery_remain_power.setProgressValue(value_f);
                                }
                            });
                        }
                        break;
                    case CAN_ID.remain_distance:// 更新剩余里程
                        //if(valid)
                        {
                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    tv_remain_distance.setText(Integer.toString(value_i));
                                }
                            });
                        }
                        break;
                    default:
                        break;
                }
            }
        });

        can0 = new CanDataThread("can0");
        can0.setListener(new CanDataThread.CanReceiveListener() {
            @Override
            public void onCanDataReceived(int channel, int can_id, byte[] data) {
                CanDataParser.getInstance().parse(can_id,data);
            }
        });
        can0.start();

        serialPortReceiveThread = new SerialPortReceiveThread();
        serialPortReceiveThread.openPort();//打开串口
        serialPortReceiveThread.start();
    }

    AnimateControl animateControl;
    AnimateControl fcwAnimationControl;
    AnimateControl ldwAnimationControl;

    Gson gson = new Gson();
    @Subscribe(threadMode = ThreadMode.MainThread)
    public void handleNaviControlMessage(ProtoMsg msg){
        if(msg.getAction().equals("updateNaviInfo")){
            final NaviUpdateInfo naviInfo = gson.fromJson(msg.getContent(),NaviUpdateInfo.class);
            handler.post(new Runnable() {
                @Override
                public void run() {
                    // 下一个路口的距离
                    tv_next_road_distance.setText(NaviUtil.getFriendlyLength(naviInfo.nextRoadDistance, NaviUtil.DistanceUnit.English));
                    // 下一个路口的转向信息 箭头等
                    iv_next_turn_tip.setBackgroundResource(
                            ResourceUtil.getIcon(MainActivity.this,
                                    "icon_type_",Integer.toString(naviInfo.nextTurnIcon)));
                }
            });
        }

        if(msg.getAction().equalsIgnoreCase("update_fcw_ldw")){
            // TODO 更新LDW 数据
            final FcwLdwUpdateInfo fcwLdwUpdateInfo = gson.fromJson(msg.getContent(), FcwLdwUpdateInfo.class);
            handler.post(new Runnable() {
                @Override
                public void run() {
                    // fcw info
                    {
                        // 路中央的车辆类型
                        if(fcwLdwUpdateInfo.fcwMsg.equalsIgnoreCase("car")){
                            fcwAnimationControl = new AnimateControl(iv_road_center, new AnimateCallback() {
                                @Override
                                public void onStartAnimation(View view) {
                                    view.setBackgroundResource(R.drawable.ldw_car);
                                }

                                @Override
                                public void onEndAnimation(View view) {
                                    view.setVisibility(View.VISIBLE);
                                }
                            });
                            fcwAnimationControl.setRepeat(true);
                            fcwAnimationControl.start();
                        }

                        if(fcwLdwUpdateInfo.fcwMsg.equalsIgnoreCase("cyclist")){
                            fcwAnimationControl = new AnimateControl(iv_road_center, new AnimateCallback() {
                                @Override
                                public void onStartAnimation(View view) {
                                    view.setBackgroundResource(R.drawable.ldw_motorcycle);
                                }

                                @Override
                                public void onEndAnimation(View view) {
                                    view.setVisibility(View.VISIBLE);
                                }
                            });
                            fcwAnimationControl.setRepeat(true);
                            fcwAnimationControl.start();
                        }

                        if(fcwLdwUpdateInfo.fcwMsg.equalsIgnoreCase("person")){
                            fcwAnimationControl = new AnimateControl(iv_road_center, new AnimateCallback() {
                                @Override
                                public void onStartAnimation(View view) {
                                    view.setBackgroundResource(R.drawable.ldw_pedistrian);
                                }

                                @Override
                                public void onEndAnimation(View view) {
                                    view.setVisibility(View.VISIBLE);
                                }
                            });
                            fcwAnimationControl.setRepeat(true);
                            fcwAnimationControl.start();
                        }

                        if(fcwLdwUpdateInfo.fcwMsg.equalsIgnoreCase("off")){
                            iv_road_center.setVisibility(View.INVISIBLE);
                            if(fcwAnimationControl !=null){
                                fcwAnimationControl.stop();
                            }
                        }
                    }
                    // ldw info
                    {
                        if(fcwLdwUpdateInfo.ldwMsg.equalsIgnoreCase("left")){
                            // 左侧车道是否碾压
                            ldwAnimationControl = new AnimateControl(iv_left_lane, new AnimateCallback() {
                                @Override
                                public void onStartAnimation(View view) {
                                    iv_left_lane.setBackgroundResource(R.drawable.ldw_left_lane_on);
                                    iv_right_lane.setBackgroundResource(R.drawable.ldw_right_lane_off);
                                }

                                @Override
                                public void onEndAnimation(View view) {
                                    iv_left_lane.setVisibility(View.VISIBLE);
                                }
                            });
                            ldwAnimationControl.setRepeat(true);
                            ldwAnimationControl.start();
                        }

                        if(fcwLdwUpdateInfo.ldwMsg.equalsIgnoreCase("right")){
                            // 右侧车道是否碾压
                            ldwAnimationControl = new AnimateControl(iv_right_lane, new AnimateCallback() {
                                @Override
                                public void onStartAnimation(View view) {
                                    iv_right_lane.setBackgroundResource(R.drawable.ldw_right_lane_on);
                                    iv_left_lane.setBackgroundResource(R.drawable.ldw_left_lane_off);
                                }

                                @Override
                                public void onEndAnimation(View view) {
                                    view.setVisibility(View.VISIBLE);
                                }
                            });
                            ldwAnimationControl.setRepeat(true);
                            ldwAnimationControl.start();
                        }

                        if(fcwLdwUpdateInfo.ldwMsg.equalsIgnoreCase("off")){
                            iv_left_lane.setBackgroundResource(R.drawable.ldw_left_lane_off);
                            iv_right_lane.setBackgroundResource(R.drawable.ldw_right_lane_off);
                            if(ldwAnimationControl!=null)
                                ldwAnimationControl.stop();
                        }
                    }
                }
            });
        }

        if(msg.getAction().equals("backlight_on")){
            // // TODO: 17-3-21 背光打开
        }

        if(msg.getAction().equals("backlight_off")){
            // // TODO: 17-3-21 背光关闭
        }

        if(msg.getAction().equalsIgnoreCase("turn_left")){
            //左转
            // Toast.makeText(this,"--->L",Toast.LENGTH_SHORT).show();
            stopAnimate();
            animateControl = new AnimateControl(iv_turn_left, new AnimateCallback() {
                @Override
                public void onStartAnimation(View view) {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            iv_tire_pressure.setVisibility(View.INVISIBLE);
                            ldw_area.setVisibility(View.INVISIBLE);
                        }
                    });
                }

                @Override
                public void onEndAnimation(View v) {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            ldw_area.setVisibility(View.VISIBLE);
                            iv_turn_left.setVisibility(View.INVISIBLE);
                        }
                    });
                }
            });
            animateControl.setRepeat(true);
            animateControl.start();
        }

        if(msg.getAction().equalsIgnoreCase("turn_right")){
            // 右转
            //Toast.makeText(this,"--->R",Toast.LENGTH_SHORT).show();
            stopAnimate();
            animateControl = new AnimateControl(iv_turn_right, new AnimateCallback() {
                @Override
                public void onStartAnimation(View view) {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            iv_tire_pressure.setVisibility(View.INVISIBLE);
                            navi_info_panel.setVisibility(View.INVISIBLE);
                        }
                    });
                }
                @Override
                public void onEndAnimation(View view) {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            ldw_area.setVisibility(View.VISIBLE);
                            navi_info_panel.setVisibility(View.VISIBLE);
                            iv_turn_right.setVisibility(View.INVISIBLE);
                        }
                    });
                }
            });
            animateControl.setRepeat(true);
            animateControl.start();
        }

        if(msg.getAction().equalsIgnoreCase("tire_pressure")){
            // 胎压
            //Toast.makeText(this,"胎压",Toast.LENGTH_SHORT).show();
            stopAnimate();
            animateControl = new AnimateControl(iv_tire_pressure, new AnimateCallback() {
                @Override
                public void onStartAnimation(View view) {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            iv_turn_left.setVisibility(View.INVISIBLE);
                            ldw_area.setVisibility(View.INVISIBLE);
                        }
                    });
                }

                @Override
                public void onEndAnimation(View view) {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            ldw_area.setVisibility(View.VISIBLE);
                            iv_tire_pressure.setVisibility(View.INVISIBLE);
                        }
                    });
                }
            });
            animateControl.setRepeat(true);
            animateControl.start();
        }

        if(msg.getAction().equalsIgnoreCase("battery")){
            //电池
            Toast.makeText(this,"电池",Toast.LENGTH_SHORT).show();
        }

        if(msg.getAction().equalsIgnoreCase("phonecall")){
            // 来电
            //Toast.makeText(this,"来电",Toast.LENGTH_SHORT).show();
            Intent intent =new Intent(this,IncommingPhonecallActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
            startActivity(intent);
        }

        if(msg.getAction().equalsIgnoreCase("show_sms")){
            //短信
            //Toast.makeText(this,"短信",Toast.LENGTH_SHORT).show();
            Intent intent =new Intent(this,IncommingSMSActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
            startActivity(intent);
        }

        if(msg.getAction().equalsIgnoreCase("close")){
            stopAnimate();
            EventBus.getDefault().post(new CloseEvent());
        }
    }

    private void stopAnimate(){
        if(animateControl!=null)
            animateControl.stop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if(can0!=null) can0.stopCAN();
        if(can1!=null) can1.stopCAN();
        if(serialPortReceiveThread!=null){
            serialPortReceiveThread.stopRun();
        }
    }
}
